package com.rzico.sbl.ui.report.manager

import com.github.mikephil.charting.animation.Easing
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.data.PieEntry
import com.github.mikephil.charting.formatter.IAxisValueFormatter
import com.github.mikephil.extend.CustomValueFormatter
import com.lzy.okgo.model.HttpMethod
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportBarrelBinding
import com.rzico.sbl.model.ManagerDate
import com.rzico.sbl.other.*
import com.rzico.sbl.ui.report.other.ReportUrl
import com.rzico.sbl.viewmodel.ReportBarrelViewModel
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.oneClick
import com.xinnuo.common.extend.optNotNull
import com.xinnuo.common.extend.startActivityEx
import com.xinnuo.common.helper.floatValue
import com.xinnuo.common.helper.intValue
import com.xinnuo.common.helper.toFormat
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import org.json.JSONObject

class ReportBarrelActivity : BaseActivity(R.layout.activity_report_barrel) {

    private val mBinding by lazy { ActivityReportBarrelBinding.bind(getRootView()) }

    private val mTotalList = ArrayList<ManagerDate>()
    private var mTotalBeginDate = getBeforeDate(6)
    private var mTotalEndDate = getTodayDate()

    private var mOutDateHint = "近7天"
    private val mOutList = ArrayList<ManagerDate>()
    private var mOutBeginDate = getBeforeDate(6)
    private var mOutEndDate = getTodayDate()

    private var mInDateHint = "近7天"
    private var mInBeginDate = getBeforeDate(6)
    private var mInEndDate = getTodayDate()

    override fun getViewModel() = get<ReportBarrelViewModel>()

    override fun initData() {
        initTitle(title = "空桶统计")

        getTotalData()
        getOutData()
        getInChartData()
    }

    override fun initListener() {
        mBinding.also {
            it.barrelAll.apply {
                initChart(
                    isCenterLabel = true,
                    isXGridLine = true,
                    isYGridLine = false,
                    xAxisMinimum = 0f,
                    yAxisMinimum = 0f,
                    xSpaceEntry = 50f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mTotalList.indices) ""
                    else
                        mTotalList[value.toInt()]
                            .date
                            .toFormat("yyyy-MM-dd", "M.d")
                }
            }

            it.barrelOut.apply {
                initChart(
                    isCenterLabel = true,
                    isXGridLine = true,
                    isYGridLine = false,
                    xLabelAngle = -45f,
                    xAxisMinimum = 0f,
                    yAxisMinimum = 0f,
                    xSpaceEntry = 50f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mOutList.indices) ""
                    else mOutList[value.toInt()].name
                }
            }

            it.barrelIn.initChart(xSpaceEntry = 40f)

            it.barrelAllTime.addTimeListener { start, end, _ ->
                mTotalBeginDate = start
                mTotalEndDate = end

                getViewModel().cancelRequest()
                getTotalData()
            }

            it.barrelOutTime.addTimeListener { start, end, hint ->
                mOutBeginDate = start
                mOutEndDate = end
                mOutDateHint = hint

                getViewModel().cancelRequest()
                getOutData()
            }

            it.barrelInTime.addTimeListener { start, end, hint ->
                mInBeginDate = start
                mInEndDate = end
                mInDateHint = hint

                getViewModel().cancelRequest()
                getInChartData()
            }

            it.barrelOutAll.oneClick {
                startActivityEx<ReportBarrelBrandActivity>(
                    "dateHint" to mOutDateHint,
                    "beginDate" to mOutBeginDate,
                    "endDate" to mOutEndDate
                )
            }

            it.barrelInAll.oneClick {
                startActivityEx<ReportBarrelBackActivity>(
                    "dateHint" to mInDateHint,
                    "beginDate" to mInBeginDate,
                    "endDate" to mInEndDate
                )
            }
        }
    }

    /**
     * 设置总数据图表数据
     */
    private fun setTotalChart() {
        mBinding
            .barrelAll
            .apply {
                if (mTotalList.none { it.quantity.intValue > 0 }
                    && mTotalList.none { it.returnQuantity.intValue > 0 }) clear()
                else {
                    setGroupData(
                        entries = arrayListOf(
                            mTotalList.mapIndexed { index, data ->
                                BarEntry(
                                    index.toFloat(),
                                    data.quantity.floatValue
                                )
                            },
                            mTotalList.mapIndexed { index, data ->
                                BarEntry(
                                    index.toFloat(),
                                    data.returnQuantity.floatValue
                                )
                            }
                        ),
                        colorList = getViewModel().barrelAllColor(),
                        labelList = listOf("出库", "入库"),
                        xFromValue = 0f,
                        formatter = CustomValueFormatter()
                    )
                }

                animateY(500)
            }
    }

    /**
     * 设置出库图表数据
     */
    private fun setOutChart() {
        mBinding
            .barrelOut
            .apply {
                if (mOutList.none { it.quantity.intValue > 0 }
                    && mOutList.none { it.returnQuantity.intValue > 0 }) clear()
                else {
                    setGroupData(
                        entries = arrayListOf(
                            mOutList.mapIndexed { index, data ->
                                BarEntry(
                                    index.toFloat(),
                                    data.quantity.floatValue
                                )
                            },
                            mOutList.mapIndexed { index, data ->
                                BarEntry(
                                    index.toFloat(),
                                    data.returnQuantity.floatValue
                                )
                            }
                        ),
                        colorList = getViewModel().barrelOutColor(),
                        labelList = listOf("出库", "入库"),
                        xFromValue = 0f,
                        formatter = CustomValueFormatter()
                    )
                }

                // 设置为可以左右滑动，放大x轴倍数
                // viewPortHandler.refresh(Matrix().apply { postScale(1.5f, 1f) }, this, false)

                animateY(500)
            }
    }

    /**
     * 设置入库饼状图数据
     */
    private fun setInChartData(
        total: Float,
        amountArray: Array<Float>
    ) {
        mBinding.barrelIn.apply {
            if (total > 0) {
                setCenterImage(
                    resId = R.mipmap.icon_barrel01,
                    drawableSize = 36f
                )

                setPieData(
                    colors = getViewModel().barrelInColor(),
                    formatter = CustomValueFormatter(),
                    PieEntry(amountArray[0], "还桶"),
                    PieEntry(amountArray[1], "外品牌1:1"),
                    PieEntry(amountArray[2], "外品牌2:1"),
                    PieEntry(amountArray[3], "外品牌3:1"),
                    PieEntry(amountArray[4], "外桶补差价"),
                    PieEntry(amountArray[5], "押桶"),
                    PieEntry(amountArray[6], "卖桶"),
                    PieEntry(amountArray[7], "退桶"),
                    PieEntry(amountArray[8], "欠桶"),
                )
            } else clear()

            animateY(1000, Easing.EaseInOutQuad)
        }
    }

    /**
     * 获取总数据图表数据
     */
    private fun getTotalData() {
        getViewModel()
            .barrelTotal(
                beginDate = mTotalBeginDate,
                endDate = mTotalEndDate,
                onSuccess = {
                    mTotalList.clear()
                    mTotalList.addItems(it)

                    setTotalChart()
                }
            )
    }

    /**
     * 获取出库图表数据
     */
    private fun getOutData() {
        getViewModel()
            .barrelOut(
                beginDate = mOutBeginDate,
                endDate = mOutEndDate,
                onSuccess = {
                    mOutList.clear()
                    mOutList.addItems(it)

                    setOutChart()
                }
            )
    }

    /**
     * 获取入库饼状图数据
     */
    private fun getInChartData() {
        getViewModel()
            .request(
                isLoadingBefore = false,
                isLoadingAfter = false,
                requestUrl = ReportUrl.getBaseUrl().zBarIn,
                requestMethod = HttpMethod.GET,
                params = arrayOf(
                    "beginDate" to mInBeginDate,
                    "endDate" to mInEndDate
                ),
                onSuccess = {
                    val obj = JSONObject(it)

                    val amountArr = arrayOf(
                        obj.optNotNull("repayQuantity").floatValue,
                        obj.optNotNull("percent1").floatValue,
                        obj.optNotNull("percent2").floatValue,
                        obj.optNotNull("percent3").floatValue,
                        obj.optNotNull("percent4").floatValue,
                        obj.optNotNull("pledgeQuantity").floatValue,
                        obj.optNotNull("buyQuantity").floatValue,
                        obj.optNotNull("refundsQuantity").floatValue,
                        obj.optNotNull("arrearsQuantity").floatValue
                    )

                    setInChartData(amountArr.sum(), amountArr)
                }
            )
    }
}